const fs = require("fs");
const path = require("path");

function capitalizeFirstLetterOfEachWord(str) {
  return str.replace(/\b\w/g, function (match) {
    return match.toUpperCase();
  });
}
// 生成name
// 生成initialState
const nameGenerator = (name) => {
  return `name: ${name} ,`;
};
//   生成initialState
const initialStateGenerator = (stateList) => {
  const initialState = {};
  stateList.forEach((item) => {
    switch (item.type) {
      case "array":
        initialState[item?.name] = [];
        break;
      case "obj":
        initialState[item?.name] = {};
        break;

      default:
        break;
    }
  });
  return `initialState: ${JSON.stringify(initialState)} ,`;
};
// 生成reducers
const reducersGenerotor = (stateList) => {
  const reducers = [];
  let str = "";
  stateList.forEach((item, index) => {
    reducers.push(`set${capitalizeFirstLetterOfEachWord(item.name)}`);
    str =
      str +
      `set${capitalizeFirstLetterOfEachWord(item.name)} (state, action) {
        state.${item.name} = action.payload
    }` +
      (index === stateList.length - 1 ? "" : ",");
  });
  const strFinished = `reducers: { ${str} }`;
  return { str: strFinished, reducers: reducers };
};

const storeGenerator = (name, reducers, strMerge) => {
  let str = `const ${name}Store = createSlice({${strMerge}});`;
  let reducerStr = "";
  reducers.map((item, index) => {
    reducerStr =
      reducerStr + ` ${item} ` + (index !== reducers.length - 1 ? "," : "");
  });
  str = `${str}const {${reducerStr}} = ${name}Store.actions;const reducer = ${name}Store.reducer;export {${reducerStr}}; export default reducer;`;
  return str;
};

(function main() {
  let str = "";
  const data = fs.readFileSync(path.resolve(__dirname, "./data.json"));
  const jsonData = JSON.parse(data);
  const { name, stateList } = jsonData;
  let nameStr = nameGenerator(name);
  let stateStr = initialStateGenerator(stateList);
  const { str: reducerStr, reducers } = reducersGenerotor(stateList);
  const strMerge = `${nameStr}${stateStr}${reducerStr}`;
  let codeSnippet = storeGenerator(name, reducers, strMerge);
  console.log("代码片段", codeSnippet);
  fs.writeFileSync(path.resolve(__dirname, "./data.js"), codeSnippet);
})();
